package com.yunyu.demo;

import android.opengl.GLES20;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.CheckBox;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.yunyu.camera.opengl.LTRTCFilterManager;
import com.yunyu.camera.opengl.LTVideoFrameFilter;

import org.webrtc.VideoFrame;

import io.agora.capture.framework.modules.channels.VideoChannel;
import io.agora.capture.framework.modules.processors.IPreprocessor;
import io.agora.capture.video.camera.CameraVideoManager;
import io.agora.capture.video.camera.Constant;
import io.agora.capture.video.camera.VideoCapture;
import io.agora.capture.video.camera.VideoCaptureFrame;

public class CameraBufferSyncActivity extends AppCompatActivity{
    private final String TAG = CameraBufferSyncActivity.class.getSimpleName();
    /**
     * 视频处理滤镜
     */
    LTVideoFrameFilter frameFilter;
    private CameraActivityHelper cameraActivityHelper;

    private CameraVideoManager mCameraVideoManager;
    private SurfaceView mVideoSurface;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frag_camera);

        initCamera();
        prepareSurfaceView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCameraVideoManager != null)
            mCameraVideoManager.stopCapture();
    }

    private void initCamera() {
        IPreprocessor preprocessor = new IPreprocessor() {
            @Override
            public VideoCaptureFrame onPreProcessFrame(VideoCaptureFrame outFrame, VideoChannel.ChannelContext context) {
                //获取共享纹理
                int shareTextureId = frameFilter.setShareTextureMode();
                //推入数据源
                frameFilter.filterNV21Data(outFrame.image, outFrame.format.getWidth(), outFrame.format.getHeight(),
                        outFrame.timestamp, outFrame.rotation);
                //获取结果
                if (shareTextureId != LTVideoFrameFilter.NO_TEXTURE){
                    outFrame.textureId = shareTextureId;
                    outFrame.format.setTexFormat(GLES20.GL_TEXTURE_2D);
                }
                return outFrame;
            }

            @Override
            public void initPreprocessor() {
                Log.d(TAG, "initPreprocessor: ");
                initFrameFilter();
            }

            @Override
            public void enablePreProcess(boolean enabled) {
                Log.d(TAG, "enablePreProcess: "+enabled);
            }

            @Override
            public void releasePreprocessor(VideoChannel.ChannelContext context) {
                Log.d(TAG, "releasePreprocessor: "+context);
                if (frameFilter != null)
                    frameFilter.destroy();
            }
        };
        mCameraVideoManager = new CameraVideoManager(this, preprocessor);

        mCameraVideoManager.setCameraStateListener(new VideoCapture.VideoCaptureStateListener() {
            @Override
            public void onFirstCapturedFrame(int width, int height) {
                Log.i(TAG, "onFirstCapturedFrame: " + width + "x" + height);
            }

            @Override
            public void onCameraCaptureError(int error, String message) {
                Log.i(TAG, "onCameraCaptureError: error:" + error + " " + message);
                if (mCameraVideoManager != null) {
                    // When there is a camera error, the capture should
                    // be stopped to reset the internal states.
                    mCameraVideoManager.stopCapture();
                }
            }
        });

        // Set camera capture configuration
        mCameraVideoManager.setPictureSize(960, 540);
//        mCameraVideoManager.setPictureSize(1280, 720);
        mCameraVideoManager.setFrameRate(24);
        mCameraVideoManager.setFacing(Constant.CAMERA_FACING_FRONT);
//        mCameraVideoManager.setLocalPreviewMirror(toMirrorMode(false));

        //切换后置摄像头
        CheckBox backCameraCB = findViewById(R.id.glBackCamera);
        backCameraCB.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mCameraVideoManager.switchCamera();
        });
    }

    private void prepareSurfaceView(){
        mVideoSurface = new SurfaceView(this);
        //设置surfaceView布局
        ConstraintLayout frameLayout = findViewById(R.id.glCameraBox);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int)(width * 16f / 9f);
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(width,height);
        frameLayout.addView(mVideoSurface,0, layoutParams);
        mCameraVideoManager.setLocalPreview(mVideoSurface, "Surface1");

        mCameraVideoManager.startCapture();
    }

    private void initFrameFilter(){
        //构造frameFilter
        frameFilter = new LTVideoFrameFilter(getApplicationContext());
        frameFilter.setListener(new LTVideoFrameFilter.Callback() {
            @Override
            public void didFilterVideoFrameDone(VideoFrame frame) {

            }

            @Override
            public void onFaceDetectedState(boolean hasFace) {
                Log.d(TAG, "onFaceDetectedState: " + hasFace);
            }
        });

        //获取控制器
        LTRTCFilterManager filterManager = frameFilter.getFilterManager();

        cameraActivityHelper = new CameraActivityHelper(CameraBufferSyncActivity.this);
        cameraActivityHelper.testControl(filterManager);
    }

    private int toMirrorMode(boolean isMirrored) {
        return isMirrored ? Constant.MIRROR_MODE_ENABLED : Constant.MIRROR_MODE_DISABLED;
    }
}
